package chatgpt;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

public class DALLERequest {

    public static void main(String[] args) {
        try {
            // 1. 读取上传的图片文件
            File imageFile = new File("D:/ruoyi/uploadPath/upload/22.jpg");
            BufferedImage image = ImageIO.read(imageFile);

            // 2. 将图像数据转换为 Base64 编码
            String base64Image = encodeImageToBase64(image);

            // 3. 构建 API 请求
            String apiUrl = "https://api.xi-ai.cn/v1/dalle-3/generate";
            String apiKey = "sk-vM175qlqxg9jT5RsBc4e402d84904c59Bc00Dc8f4fCf1640";
            String prompt = "Generate an image based on the uploaded picture.";

            // 4. 发送 API 请求
            String requestBody = String.format("{\"prompt\": \"%s\", \"image\": \"%s\"}", prompt, base64Image);
            String response = sendAPIRequest(apiUrl, apiKey, requestBody);

            // 5. 处理 API 响应（根据实际需求解析 JSON 等）
            System.out.println("API Response: " + response);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String encodeImageToBase64(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    private static String sendAPIRequest(String apiUrl, String apiKey, String requestBody) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + apiKey);

        // 设置请求体
        StringEntity entity = new StringEntity(requestBody);
        httpPost.setEntity(entity);

        // 执行请求并获取响应
        HttpResponse response = httpClient.execute(httpPost);

        // 读取响应内容
        StringBuilder result = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        }

        return result.toString();
    }
}
